package cn.oniokey.waterDetection.config;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public record BaseResponse<T>(int code, String message, T data) {
    private static final ObjectMapper objectMapper = new ObjectMapper();

    /**
     * 成功-无数据
     */
    public static <T> BaseResponse<T> success() {
        return new BaseResponse<>(ResultCode.RC200.getCode(), ResultCode.RC200.getMessage(), null);
    }

    /**
     * 成功-携带数据
     *
     * @param data 数据
     */
    public static <T> BaseResponse<T> success(T data) {
        return new BaseResponse<>(ResultCode.RC200.getCode(), ResultCode.RC200.getMessage(), data);
    }

    /**
     * 失败-无数据
     */
    public static <T> BaseResponse<T> failure() {
        return new BaseResponse<>(ResultCode.RC900.getCode(), ResultCode.RC900.getMessage(), null);
    }

    /**
     * 失败-无数据(非 900 返回码)
     */
    public static <T> BaseResponse<T> failure(ResultCode code) {
        return new BaseResponse<>(code.getCode(), code.getMessage(), null);
    }

    /**
     * 转换为 JSON 字符串
     *
     * @return JSON 字符串
     * @throws JsonProcessingException JSON 转换异常
     */
    public String asJsonString() throws JsonProcessingException {
        return objectMapper.writeValueAsString(this);
    }

}
